package tripx.blog;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import tripx.sql.SqlAction;

/**
 * Store the information in the configuration file
 * 
 * @author zhb
 * 
 */
public class BlogServiceConfig {

	private static BlogServiceConfig config;

	private ArrayList<SqlAction> queryActionList;

	private String imageBaseDir;

	private Document configDoc;

	private BlogServiceConfig() {
		queryActionList = new ArrayList<SqlAction>();
		loadConfigDoc();
		loadQueryActionList();
		loadImageBaseDir();
	}

	public static BlogServiceConfig getInstance() {
		if (config == null) {
			config = new BlogServiceConfig();
		}
		return config;
	}

	private void loadConfigDoc() {
		File config = new File("./config/blog.xml");
		if (!config.exists()) {
			// file not found
		} else {
			try {
				configDoc = DocumentBuilderFactory.newInstance()
						.newDocumentBuilder().parse(config);
			} catch (SAXException | IOException | ParserConfigurationException e) {

			}
		}
	}

	/**
	 * read file and load the query action list.
	 */
	private void loadQueryActionList() {
		Element root = configDoc.getDocumentElement();
		NodeList actionNodeList = root.getElementsByTagName("action");
		for (int i = 0; i < actionNodeList.getLength(); i++) {
			Element e = (Element) actionNodeList.item(i);
			SqlAction action = new SqlAction(e.getAttribute("key"),
					e.getAttribute("sql"), Integer.parseInt(e
							.getAttribute("paramCount")));
			queryActionList.add(action);
		}
	}

	/**
	 * fetch the attribute which tells the base directory
	 */
	private void loadImageBaseDir() {
		Element root = configDoc.getDocumentElement();
		Element image = (Element) (root.getElementsByTagName("image").item(0));
		imageBaseDir = image.getAttribute("basedir");
	}

	/**
	 * get the the list of QueryAction
	 * 
	 * @return
	 */
	public ArrayList<SqlAction> getQueryActionList() {
		return queryActionList;
	}

	/**
	 * get the Image Base Directory which saves all the Images
	 * 
	 * @return
	 */
	public String getImageBaseDirPath() {
		return imageBaseDir;
	}
}
